import React, { Component } from 'react';
import { routerRedux, Route, Switch, Link } from 'dva/router';
// import { routerRedux,Link } from 'dva/router';

import Debounce from 'lodash-decorators/debounce';
import Bind from 'lodash-decorators/bind';
import { connect } from 'dva';
import {
  Button, Menu, Dropdown, Icon, Row, Col,
  Input, InputNumber,
  Steps, Card, Popover, Badge, Table, Tooltip, Divider,
  Checkbox, Modal, Radio,
  Select, message, Collapse,
  Form, Upload, Spin, Tag
} from 'antd';
const Panel = Collapse.Panel;
import classNames from 'classnames';
import PageHeaderLayout from '../../layouts/PageHeaderLayout';
import DescriptionList from '../../components/DescriptionList';
import styles from './ApplyProfile.less';
import { create } from 'domain';
import u620 from '../../assets/u620.png';
import u622 from '../../assets/u622.png';
import querystring from 'querystring';
import { solo } from '../../common/solo';

import { getRoutes } from '../../utils/utils';


const { Step } = Steps;
const TextArea = Input.TextArea;
const { Description } = DescriptionList;
const ButtonGroup = Button.Group;
const RadioGroup = Radio.Group;
const Option = Select.Option;

const getWindowWidth = () => (window.innerWidth || document.documentElement.clientWidth);

export let profileState = false;

@connect(({ pendingTask }) => ({
  pendingTask,
}))
@Form.create()
export default class CompleteApplyDetails extends Component {
  state = {
    id: '',
    reviewState: '',
    stepDirection: 'horizontal',
    modalVisible: false,
    submitting: false,
    progressVisible: false,
    custList: {},
    taskList: {},
    auditList: [],
    approvalRecordList: []
  }

  componentDidMount() {
    const { dispatch, location } = this.props;
    const params = querystring.parse(location.search.slice(1));
    
    this.setState({
      id: params.id,
      state: params.state,
    });
    dispatch({
      type: 'pendingTask/fetchApplyProfile',
      payload: {
        id: params.id,
      },
      callback: () => {
        const { pendingTask: { custMessgeList, custTaskList, custAuditList, custListLoading } } = this.props;
       
        this.setState({
          custListLoading: custListLoading,
          custList: custMessgeList,
          taskList: custTaskList,
          //auditList: custAuditList
        })
        if (custTaskList.taskName == "初审") {
          this.setState({
            reviewState: 1,
          })
        } else if (custTaskList.taskName == "复审") {
          this.setState({
            reviewState: 2,
          })
        } else if (custTaskList.taskName == "终审") {
          this.setState({
            reviewState: 3,
          })
        }
        dispatch({
          type: 'pendingTask/showAllAudit',
          payload: {
            applyId: custMessgeList.id,
          },
          callback: () => {
            const { pendingTask: { auditsList } } = this.props;
            // console.log("audits",auditsList)
            let auditsAllList = [];
            this.setState({
              auditList: auditsList
            })
          }
        })
        dispatch({
          type: 'pendingTask/approvalRecord',
          payload: {
            applyId: custMessgeList.id,//"992290496124190722",//
          },
          callback: () => {
            const { pendingTask: { approvalRecordList, approvalLoading } } = this.props;
            if (approvalRecordList.length > 0) {
              this.setState({
                approvalRecordList: approvalRecordList,
              })
            }
          }
        });
      }
    });
    this.setStepDirection();
    window.addEventListener('resize', this.setStepDirection);
  }

  // componentWillUnmount() {
  //   window.removeEventListener('resize', this.setStepDirection);
  //   this.setStepDirection.cancel();
  // }

  @Bind()
  @Debounce(200)
  setStepDirection() {
    const { stepDirection } = this.state;
    const w = getWindowWidth();
    if (stepDirection !== 'vertical' && w <= 576) {
      this.setState({
        stepDirection: 'vertical',
      });
    } else if (stepDirection !== 'horizontal' && w > 576) {
      this.setState({
        stepDirection: 'horizontal',
      });
    }
  }

  handleTabChange = (key) => {
    const { dispatch, match } = this.props;
    switch (key) {
      case 'customer':
        dispatch(routerRedux.push(`/review/complete-apply-details/complete1?id=${this.state.id}&custId=${this.state.custList.id}&taskId=${this.state.taskList.id}&reviewState=${this.state.reviewState}`));
        break;
      case 'business':
        dispatch(routerRedux.push(`/review/complete-apply-details/complete2?id=${this.state.id}&custId=${this.state.custList.id}&taskId=${this.state.taskList.id}&reviewState=${this.state.reviewState}`));
        break;
      case 'credits':
        dispatch(routerRedux.push(`/review/complete-apply-details/complete3?id=${this.state.id}&custId=${this.state.custList.id}&taskId=${this.state.taskList.id}&reviewState=${this.state.reviewState}`));
        break;
      case 'pay':
        dispatch(routerRedux.push(`/review/complete-apply-details/complete4?id=${this.state.id}&custId=${this.state.custList.id}&taskId=${this.state.taskList.id}&reviewState=${this.state.reviewState}`));
        break;
      case 'guarantee':
        dispatch(routerRedux.push(`/review/complete-apply-details/complete5?id=${this.state.id}&custId=${this.state.custList.id}&taskId=${this.state.taskList.id}&reviewState=${this.state.reviewState}`));
        break;
      case 'suggestion':
        dispatch(routerRedux.push(`/review/complete-apply-details/complete6?id=${this.state.id}&custId=${this.state.custList.id}&taskId=${this.state.taskList.id}&reviewState=${this.state.reviewState}`));
        break;
        break;
      default:
        break;
    }
  }

  tabList = [{
    key: 'customer',
    tab: '客户信息核实',
  }, {
    key: 'business',
    tab: '业务情况核实',
  }, {
    key: 'credits',
    tab: '资信情况调查',
  }, {
    key: 'pay',
    tab: '还款能力调查',
  }, {
    key: 'guarantee',
    tab: '担保情况调查',
  }, {
    key: 'suggestion',
    tab: '审核意见',
  }];

  handleProgress = () => {
    this.state.approvalRecordList.length > 0 ?
      this.setState({
        progressVisible: true
      })
      :
      message.warning("暂无审批记录")
  }
  handleProgressModalCancel = () => {
    this.setState({
      progressVisible: false
    })
  }
  hanleProgressModalOk = () => {
    this.setState({
      progressVisible: false
    })
  }

  progressColumns = [
    {
      title: '指标',
      dataIndex: 'name',
      key: 'name',
      width: 150,
    },
    {
      title: '初审状态',
      dataIndex: 'state1',
      key: 'state1',
      render: (text, item) => {
        return (
          <div>
            {
              item.childrens.map((child) => {
                if (child.state1 == 1) {
                  return <Tag color='green'>{child.name}  <Icon type="check" style={{ color: 'green' }} /></Tag>;
                }
                if (child.state1 == 2) {
                  return <Tag color='red'>{child.name} <Icon type="close" style={{ color: 'red' }} /></Tag>;
                }
                if (child.state1 == null) {
                  if (child.name == "偿债意愿核实") {
                    return;
                  }
                  return <Tag >{child.name} <Icon type="minus" style={{ color: 'gray' }} /></Tag>;
                }
              })}
          </div>);
      }
    },
    {
      title: '复审状态',
      dataIndex: 'state2',
      key: 'state2',
      render: (text, item) => {
        return (
          <div>
            {
              item.childrens.map((child) => {
                if (child.state2 == 1) {
                  return <Tag color='green'>{child.name}  <Icon type="check" style={{ color: 'green' }} /></Tag>;
                }
                if (child.state2 == 2) {
                  return <Tag color='red'>{child.name} <Icon type="close" style={{ color: 'red' }} /></Tag>;
                }
                if (child.state2 == null) {
                  return <Tag >{child.name} <Icon type="minus" style={{ color: 'gray' }} /></Tag>;;
                }
              })}
          </div>);
      }
    },
  ];

  renderDescription = () => {
    return (
      this.state.custList &&
      <DescriptionList className={styles.headerList} size="small" col="3">
        <Description term="客户名称">{this.state.custList.custName}</Description>
        <Description term="证件号">{this.state.custList.idno}</Description>
        <Description term="担保公司">{this.state.custList.orgName}</Description>
        <Description term="经销商">{this.state.custList.dealer}</Description>
        <Description term="所购车型">{this.state.custList.carType}</Description>
        <Description term="车辆类型">{this.state.custList.carClass == 1 ? "新车" : "二手车"}</Description>
        <Description term="车价">{this.state.custList.carPrice}</Description>
        <Description term="分期金额">{this.state.custList.loanAmount}</Description>
        <Description term="分期数">{this.state.custList.duration}</Description>
      </DescriptionList>
    );
  };

  handleClickShow = () => {
    this.setState({
      modalVisible: true
    })
  }
  hanleCreateUserModalOk = () => {
    this.setState({
      modalVisible: false
    })
  }
  handleModalCancel = () => {
    this.setState({
      modalVisible: false
    })
  }

  render() {
    const { stepDirection } = this.state;
    // const { pendingTask: { custMessgeList, idcardVerifyList, custtaskList, loadingCust } } = this.props;
    const { getFieldDecorator, getFieldValue } = this.props.form;
    const description = this.renderDescription();

    const { match, routerData, location } = this.props;
    const routes = getRoutes(match.path, routerData);
    const img = (<img alt="" src={u620} />);
    const { pathname, params, search } = location;
    let approvalId = 0;
    let tabActiveKey = 'customer';
    if (pathname.indexOf('complete2') > -1) {
      tabActiveKey = 'business';
    } else if (pathname.indexOf('complete3') > -1) {
      tabActiveKey = 'credits';
    } else if (pathname.indexOf('complete4') > -1) {
      tabActiveKey = 'pay';
    } else if (pathname.indexOf('complete5') > -1) {
      tabActiveKey = 'guarantee';
    } else if (pathname.indexOf('complete6') > -1) {
      tabActiveKey = 'suggestion';
    }

    const { pendingTask: { custAuditList, approvalLoading } } = this.props;

    const menu = (
      <Menu>
        <Menu.Item key="1">
          <a
            target="_blank"
            href={`${solo.pdfDownloadUrl}${this.state.custList.id}`}>
            {/* href={`http://192.168.2.154:9050/v1/apply/downloadPdf/${this.state.custList.id}`}> */}
            调查报告下载
          </a>
        </Menu.Item>
      </Menu>
    );

    const action = (
      <div>
        <ButtonGroup>
          <Button onClick={this.handleClickShow}>审批结果</Button>
          <Button onClick={this.handleProgress}>审批记录</Button>
          <Dropdown overlay={menu} placement="bottomRight">
            <Button><Icon type="ellipsis" /></Button>
          </Dropdown>
        </ButtonGroup>
      </div>
    );
    return (
      <Row >
        {/* {JSON.stringify(this.state.auditList) } */}
        <PageHeaderLayout
          title="客户信息核实"
          logo={<img alt="" src="https://gw.alipayobjects.com/zos/rmsportal/nxkuOJlFJuAUhzlMTCEe.png" />}
          content={description}
          tabList={this.tabList}
          tabActiveKey={tabActiveKey}
          onTabChange={this.handleTabChange}
          action={action}
        >
          <Col span={3}>
            客户信息核实 {img}<br /><br />
            业务情况核实 {img}<br /><br />
            资信情况调查 {img}<br /><br />
            还款能力调查 {img}<br /><br />
            担保情况调查 {img}<br /><br />
          </Col>
          <Switch>
            {
              routes.map(item =>
                (
                  <Route
                    key={item.key}
                    path={item.path}
                    component={item.component}
                    exact={item.exact}
                  />
                )
              )
            }
          </Switch>
          <Modal
            title={'审批结果'}
            visible={this.state.modalVisible}
            onCancel={this.handleModalCancel}
            keyboard={true}
            footer={null}
          >
            <Table
              columns={this.progressColumns}
              dataSource={this.state.auditList.all}
              size="small"
              rowKey="key"
              bordered={false}
              pagination={false}
              style={{ marginBottom: 20 }}
            />
          </Modal>
          <Modal
            title='审批记录'
            visible={this.state.progressVisible}
            keyboard={true}
            footer={null}
            onCancel={this.handleProgressModalCancel}
          >
          
            <Collapse>
              {
                approvalLoading ?
                  <div className={styles.spinContainer}>
                    <Spin size="large" />
                  </div>
                  :
                  this.state.approvalRecordList && this.state.approvalRecordList.map((item) => {
                    return (
                      <Panel header={item.displayName + "  " + item.finishTime} key={item.id}>
                        <p>任务名称：{item.displayName}</p>
                        <p>创建时间：{item.createTime}</p>
                        <p>完成时间：{item.finishTime}</p>
                        <p>任务处理人：{item.opname}</p>
                        <p>任务处理结果：{item.result}</p>
                        <p>意见：{item.content}</p>
                      </Panel>
                    )
                  })
              }
            </Collapse>
          </Modal>
        </PageHeaderLayout>
      </Row >
    );
  }
}
